package org.simpleframework.mvc;

import org.simpleframework.aop.AspectWeaver;
import org.simpleframework.core.BeanContainer;
import org.simpleframework.inject.DependencyInjector;
import org.simpleframework.mvc.processor.RequestProcessor;
import org.simpleframework.mvc.processor.impl.ControllerRequestProcessor;
import org.simpleframework.mvc.processor.impl.JspRequestProcessor;
import org.simpleframework.mvc.processor.impl.PreRequestProcessor;
import org.simpleframework.mvc.processor.impl.StaticResourceRequestProcessor;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 〈〉
 *
 * @author Noah2021
 * @create 2021/3/6
 * @return
 *
 * / 与 /* 的区别
 * /：会过滤几乎所有的请求，除了 jsp 文件的请求
 *
 * req.getRequestDispatcher("/WEB-INF/jsp/hello.jsp").forward(req,resp);
 * /*：会过滤几乎所有的请求，包括 jsp 文件的请求如果 service 方法里包含上面（转发）的代码会一直陷入死循环
 *     因为转发本质就是一个 doGet 请求，会被 /* 拦截再次进入 service方法周而复始
 *
 *
 *
 * 测试案例
 *
 * maven 运行添加 tomcat7:run
 *
 * 静态资源：
 * http://localhost:8080/simpleframework/static/promotion.png
 * json：
 * http://localhost:8080/simpleframework/headline/query?id=3
 * jsp:
 * http://localhost:8080/simpleframework/templates/addheadline.jsp
 *
 *
 *
 */
@WebServlet("/*")
public class DispatcherServlet extends HttpServlet {

    List<RequestProcessor> PROCESSOR = new ArrayList<RequestProcessor>();

    @Override
    public void init() throws ServletException {
        //1.初始化容器
        BeanContainer beanContainer = BeanContainer.getInstance();
        beanContainer.loadBeans("com.noah2021");
        new AspectWeaver().doAop();
        new DependencyInjector().doIoc();
        //2.初始化请求处理器责任链
        PROCESSOR.add(new PreRequestProcessor());
        PROCESSOR.add(new StaticResourceRequestProcessor(getServletContext()));
        PROCESSOR.add(new JspRequestProcessor(getServletContext()));
        PROCESSOR.add(new ControllerRequestProcessor());
    }
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.创建责任链对象的实例
        RequestProcessorChain requestProcessorChain = new RequestProcessorChain(PROCESSOR.iterator(), req, resp);
        //2.通过责任链模式来依次调用请求处理器对请求进行处理
        requestProcessorChain.doRequestProcessChain();
        //3.对处理结果进行渲染
        requestProcessorChain.doRender();
    }

    @Override
    public void destroy() {
        System.out.println("destory...");
    }

}